package com.example.servlet.student;

import com.example.bean.Student2;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

/**
 * @program: sms
 * @description:
 * @author: zhanghz001
 * @create: 2020-11-02 14:57
 **/
@WebServlet("/listStudent")
public class ListStudentServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path = getServletContext().getRealPath("/student/student.txt");
        ArrayList<Student2> list = new ArrayList<>();
        try (BufferedReader br = new BufferedReader(new FileReader(path));) {
            String line;
            while ((line = br.readLine()) != null && !"".equals(line)) {
                String[] split = line.split(",");
                String username = split[0];
                String ageStr = split[1];
                String scoreStr = split[2];
                list.add(new Student2(username, Integer.parseInt(ageStr), Integer.parseInt(scoreStr)));
            }
            req.setAttribute("list", list);
            req.getRequestDispatcher("/listStudent.jsp").forward(req, resp);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }

    }

    protected void doGet1(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path = getServletContext().getRealPath("/student/student.txt");
        ArrayList<Student2> list = new ArrayList<>();
        try (BufferedReader br = new BufferedReader(new FileReader(path));) {
            String line;
            while ((line = br.readLine()) != null && !"".equals(line)) {
                String[] split = line.split(",");
                String username = split[0];
                String ageStr = split[1];
                String scoreStr = split[2];
                list.add(new Student2(username, Integer.parseInt(ageStr), Integer.parseInt(scoreStr)));
            }
            //展示
            resp.setContentType("text/html;charset=utf-8");
            PrintWriter writer = resp.getWriter();
            for (Student2 student : list) {
                writer.write(student.toString());
                writer.write("<br>");
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }

    }
}
